#include "database.h"
#include <QStringList>
#include <QDir>

#include "common.h"
#include "databasequery.h"
#include <QSqlError>
#include <QTime>
#include "DataBase/dbtab_mashwelder.h"
#include "DataBase/dbtab_user.h"
#include "DataBase/dbtab_misc.h"
#include "DataBase/dbtab_warn.h"
#include "DataBase/dbtab_productionorder.h"
#include "tdebug.h"

#undef USE_MYSQL

DataBase *DataBase::mDbInstance = NULL;
int DataBase::getDataBaseVersion(QSqlDatabase &db)
{
    QString s=DBTab_Misc::getValue(DBTab_Misc::VERSION,db);
    return s.toInt();
}

void DataBase::setDataBaseVersion(int version, QSqlDatabase &db)
{
    DBTab_Misc::setValue(DBTab_Misc::VERSION,QString::number(version),db);
}

DataBase::DataBase(QObject *parent,const QString &connect_name) :
    QObject(parent)
{
    Q_UNUSED(connect_name);
    QDir dir = QDir(PATH_DATABASE);
    if(!dir.exists())
    {
        dir.mkdir(PATH_DATABASE);
    }
    DDDValue(QSqlDatabase::drivers());
    mDb = QSqlDatabase::addDatabase("QSQLITE","normal");
    mDb.setDatabaseName(COM_DIR DATABASE_NAME);
    DDDValue(COM_DIR DATABASE_NAME);
    TSystem2("sudo chmod -R 777 " + QString(COM_DIR DATABASE_NAME));
    mDb.setUserName("john");
    mDb.setPassword("l123...");
    if(!mDb.open())
    {
        qDebug("mDb.open() fail!");
    }
    mDb.close();
    createAllTabs(mDb);
}

void DataBase::createAllTabs(QSqlDatabase &db)
{
    db.open();
    db.tables();
    QStringList tabs = db.tables();
    if(!tabs.contains(DBTab_Misc::TAB_MISC))
        DBTab_Misc::createTab(db);
    if(!tabs.contains(DBTab_MashWelder::TAB_MASHWELDER))
        DBTab_MashWelder::createTab(db);
    if(!tabs.contains(DBTab_User::TAB_USER))
        DBTab_User::createTab(db);
    if(!tabs.contains(DBTab_Warn::TAB_WARN))
        DBTab_Warn::createTab(db);
    if(!tabs.contains(DBTab_ProductionOrder::TAB_ORDER))
        DBTab_ProductionOrder::createTab(db);
    DBTab_User::initTable(db);
    DBTab_Warn::initTable(db);
    DBTab_MashWelder::initTable(db);
    DataBase::setDataBaseVersion(DATABASE_VERSION_NOW,db);
    db.close();
}

QSqlDatabase DataBase::dataBase()
{
    return mDb;
}

QSqlDatabase& DataBase::getDataBase()
{
    if(mDbInstance==NULL)
    {
        mDbInstance = new DataBase();
    }
    return mDbInstance->mDb;
}
